package com.coocaa.typhoon.api.config.nacosjasypt;

import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author bijiahao
 * @date : 2025/9/16 16:50
 * @description
 */
@Configuration
@Slf4j
public class JasyptConfig {
    private ConfigurableApplicationContext context;

    @Bean("primaryEncryptor")
    public StringEncryptor primaryEncryptor() {
        String pwd = getPwd("jasypt.encryptor.password");
        log.info("primaryEncryptor :{}", pwd);
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(decrypt(pwd));
        config.setAlgorithm("PBEWithMD5AndDES");
        encryptor.setConfig(config);
        return encryptor;
    }

    /**
     * 第二套秘钥，如果有需要可以配置多套秘钥
     */
    @Bean("secondaryEncryptor")
    public StringEncryptor secondaryEncryptor() {
        String pwd = getPwd("jasypt.encryptor.password2");
        log.info("secondaryEncryptor :{}", pwd);
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(decrypt(pwd));
        config.setAlgorithm("PBEWithMD5AndDES");
        encryptor.setConfig(config);
        return encryptor;
    }

    /**
     * 从启动参数或者配置中获取密码
     *
     * @param key 配置key
     * @return 密码
     */
    private String getPwd(String key) {
        String pwd = System.getProperty(key);
        if (StringUtils.isBlank(pwd)) {
            pwd = context.getEnvironment().getProperty(key);
        }
        if (StringUtils.isBlank(pwd)) {
            pwd = "12345678";
        }
        return pwd;
    }

    /**
     * 二次解密
     *
     * @param pwd 运维提供的加密密码
     * @return 解密后的密码
     */
    private String decrypt(String pwd) {
        //截取字符串，去掉前6位和后2为，默认规则
        return pwd.substring(6, pwd.length() - 2);
    }

    @Bean
    public EncryptablePropertyResolver encryptablePropertyResolver(
            @Qualifier("primaryEncryptor") StringEncryptor primaryEncryptor,
            @Qualifier("secondaryEncryptor") StringEncryptor secondaryEncryptor) {
        return new MultiKeyPropertyResolver(primaryEncryptor, secondaryEncryptor);
    }

    @Autowired
    public void setContext(ConfigurableApplicationContext context) {
        this.context = context;
    }
}